package com.bright.dao.Impl;

import com.bright.dao.BaseDao;
import com.bright.dao.OssDao;
import com.bright.entity.Oss;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OssDaoImpl extends BaseDao implements OssDao {
    @Override
    public List<Oss> selectAll() {
        String sql = "SELECT * FROM `oss` ORDER BY bucketName ASC";
        List<Oss> ossList = new ArrayList<>();
        ResultSet rs = executeQuery(sql);
        if(rs!=null){
            try{
                while (rs.next()){
                    Oss oss = new Oss();
                    oss.setId(rs.getInt("id"));
                    oss.setBucketName(rs.getString("bucketName"));
                    oss.setType(rs.getString("type"));
                    oss.setCapacity(rs.getLong("capacity"));
                    oss.setFlow(rs.getLong("flow"));
                    oss.setVisits(rs.getInt("visits"));
                    oss.setPermission(rs.getString("permission"));
                    ossList.add(oss);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                closedAll(rs);
            }

        }
        return ossList;
    }

    @Override
    public Oss selectByName(String name) {
        String sql = "SELECT * FROM `oss` where bucketName = ?";
        ResultSet rs = executeQuery(sql,name);
        if(rs!=null){
            try{
                while (rs.next()){
                    Oss oss = new Oss();
                    oss.setId(rs.getInt("id"));
                    oss.setBucketName(rs.getString("bucketName"));
                    oss.setType(rs.getString("type"));
                    oss.setCapacity(rs.getLong("capacity"));
                    oss.setFlow(rs.getLong("flow"));
                    oss.setVisits(rs.getInt("visits"));
                    oss.setPermission(rs.getString("permission"));
                    return oss;
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                closedAll(rs);
            }
        }
        return null;
    }

    @Override
    public int insert(Oss oss) {
        String sql = "insert into `oss` (bucketName,type,permission) values (?,?,?)";
        return executeUpdate(sql,oss.getBucketName(),oss.getType(),oss.getPermission());
    }

    @Override
    public int updatePermission(String name, String permission) {
        String sql = "update oss set permission = ? where bucketName = ?";
        return executeUpdate(sql,permission,name);
    }
}
